<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;
use app\models\AuthRule;
use mdm\admin\components\Configs;
use mdm\admin\components\Helper;
use app\models\search\AuthItemSearch;
use mdm\admin\models\AuthItem;
use yii\helpers\ArrayHelper;

class QxPositionController extends CommonController
{
    public function actionList()
    {
        $searchModel = new AuthItemSearch();
        $searchModel->type = 3;
        $dataProvider = $searchModel->search(\Yii::$app->request->getQueryParams());
        $all = array_values(ArrayHelper::toArray($dataProvider->models,'post'));
        $count = $dataProvider->count;
        //必须要把数组转化为对象，前端固定的格式s
        return $this->actionLayData($count,$all);
    }
    public function actionCreate()
    {
        $model = new \app\models\AuthItem(null);
        $model->created_at = time();
        if ($model->load(\Yii::$app->getRequest()->post()) && $model->save()) {
            return $this->dealFD('新增成功',1);
        } else {
            return $this->dealFD($model->getErrors(),0);
        }
    }
    public function actionUpdate($id)
    {
        $model = \app\models\AuthItem::findOne($id);
        $post = \Yii::$app->getRequest()->post();
        $model->name = $post['AuthItem']['name'];
        $model->updated_at = time();
        $model->description = $post['AuthItem']['description'];
        if ($model->save()) {
            return $this->dealFD('新增成功',1);
        } else {
            return $this->dealFD($model->getErrors(),0);
        }
    }
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $opts = $this->getItems_($model);
        $res['data'] = $opts;
        $res['res'] = 1;
        return json_encode($res);
    }
    public function getItems_($model)
    {
        $item = new \app\models\AuthItem();
        $all = $item->find()->where(['type'=>3])->all();
        $available = [];
        foreach ($all as $item) {
            $available[$item->name] = $item->name;
        }
        $assigned = [];
        $itemChild = new AuthItemChild();
        $items = $itemChild->find()->where(['parent'=>$model->name])
            ->select('i.*,auth_item_child.*')
            ->leftJoin('auth_item as i','i.name=auth_item_child.parent')
            ->asArray()
            ->all();
        foreach ($items as $item) {
            $assigned[$item['child']] = $item['child'];
            unset($available[$item['child']]);
        }
        unset($available[$model->name]);
        return [
            'available' => $available,
            'assigned' => $assigned,
        ];
    }
    public function actionDelete($id)
    {
        $model = new \app\models\AuthItem();
        $model = $model->find()->where(['name'=>$id])->one();
        if ($model->delete()) {
            return $this->dealFD('删除成功',1);
        } else {
            return $this->dealFD($model->getErrors(),0);
        }
    }
}